<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Db;
use think\Loader;
use think\exception\HttpException;
use think\Config;

class Card extends Controller
{
//    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("number")) {
            $map['number'] = ["like", "%" . $this->request->param("number") . "%"];
        }
        if ($this->request->param("batch")) {
            $map['batch'] = ["like", "%" . $this->request->param("batch") . "%"];
        }
        if ($this->request->param("realname")) {
            $map['realname'] = ["like", "%" . $this->request->param("realname") . "%"];
        }
        if ($this->request->param("mobile")) {
            $map['mobile'] = ["like", "%" . $this->request->param("mobile") . "%"];
        }
        if ($this->request->param("name")) {
            $map['name'] = ["like", "%" . $this->request->param("name") . "%"];
        }
        if ($this->request->param("tel")) {
            $map['tel'] = ["like", "%" . $this->request->param("tel") . "%"];
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $model = new \app\common\model\Cards();

        // 列表过滤器，生成查询Map对象
        $map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete]);

        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }

        $this->datalist($model, $map);

        //获取该批次号
        $batch = (isset($map['batch'][1]))?trim($map['batch'][1],'%'):'';

        return $this->view->fetch('index',['batch'=>$batch]);
    }


//    /**
//     * 添加
//     * @return mixed
//     */
//    public function add()
//    {
//        $controller = $this->request->controller();
//
//        if ($this->request->isAjax()) {
//            // 插入
//            $data = $this->request->except(['id']);
//
//            // 验证
//            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
//                $validate = new $validateClass();
//                if (!$validate->check($data)) {
//                    return ajax_return_adv_error($validate->getError());
//                }
//            }
//
//            // 写入数据
//            if (
//                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
//                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
//            ) {
//                //使用模型写入，可以在模型中定义更高级的操作
//                $model = new $modelClass();
//                $ret = $model->isUpdate(false)->save($data);
//            } else {
//                // 简单的直接使用db写入
//                Db::startTrans();
//                try {
//                    $model = Db::name($this->parseTable($controller));
//                    $ret = $model->insert($data);
//                    // 提交事务
//                    Db::commit();
//                } catch (\Exception $e) {
//                    // 回滚事务
//                    Db::rollback();
//
//                    return ajax_return_adv_error($e->getMessage());
//                }
//            }
//
//            return ajax_return_adv('添加成功');
//        } else {
//            // 添加
//            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
//        }
//    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            $mobile = $data['mobile'];
            $tel    = $data['tel'];
            unset($data['mobile']);
            unset($data['tel']);
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }

            $sales_id    = Db::name('sale')->where('mobile',$mobile)->value('id');
            $offline_id  = Db::name('offline')->where('tel',$tel)->value('id');

            if(empty($sales_id)){
                $data['sales_id'] = 0;
            }else{
                $data['sales_id'] = $sales_id;
            }

            if(empty($offline_id)){
                $data['offline_id'] = 0;
            }else{
                $data['offline_id'] = $offline_id;
            }


            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 更新数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                // 使用模型更新，可以在模型中定义更高级的操作
                $model = new $modelClass();
                $ret = $model->isUpdate(true)->save($data, ['id' => $data['id']]);
            } else {
                // 简单的直接使用db更新
                Db::startTrans();
                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->where('id', $data['id'])->update($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv("编辑成功");
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel($controller)->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }

            //查询是否绑定 销售和快递  并查询对应电话 返回到页面
            $sales_id = Db::name('card')->where('id',$id)->value('sales_id');
            $offline_id = Db::name('card')->where('id',$id)->value('offline_id');

            if($sales_id != 0){
                $mobile   = Db::name('admin_user')->where('id',$sales_id)->value('mobile');
            }else{
                $mobile = '';
            }

            if($offline_id != 0){
                $tel   = Db::name('admin_user')->where('id',$offline_id)->value('tel');
            }else{
                $tel = '';
            }

            $this->view->assign("vo", $vo);
            $this->view->assign("mobile", $mobile);
            $this->view->assign("tel", $tel);

            return $this->view->fetch();
        }
    }

    /**
     * 默认删除操作
     */
    public function delete()
    {
//        return $this->updateField($this->fieldIsDelete, 1, "移动到回收站成功");
        $model = $this->getModel();
        $pk = $model->getPk();
        $ids = $this->request->param($pk);
        $where[$pk] = ["in", $ids];
        if (false === $model->where($where)->delete()) {
            return ajax_return_adv_error($model->getError());
        }

        return ajax_return_adv("删除成功");
    }


    /**
     * 保存排序
     */
    public function saveOrder()
    {
        $param = $this->request->param();
        if (!isset($param['sort'])) {
            return ajax_return_adv_error('缺少参数');
        }

        $model = $this->getModel();
        foreach ($param['sort'] as $id => $sort) {
            $model->where('id', $id)->update(['sort' => $sort]);
        }

        return ajax_return_adv('保存排序成功', '');
    }

    /**
     * Excel导出
     */
    public function Excel(){
        $form = $this->request->post();
        //自定义模糊查询
        $where = ' where a.isdelete = '.$this::$isdelete.' ';
        foreach($form as $k=>$v) {
            if(!empty($v)) {
                if('number' == $k) {
                    $where .= " and a.number like '%".$v."%'";
                }
                if('batch' == $k) {
                    $where .= " and b.batch like '%".$v."%'";
                }
                if('realname' == $k) {
                    $where .= " and c.realname like '%".$v."%'";
                }
                if('mobile' == $k) {
                    $where .= " and c.mobile like '".$v."%'";
                }
                if('name' == $k) {
                    $where .= " and d.name like '%".$v."%'";
                }
                if('tel' == $k) {
                    $where .= " and d.tel like '".$v."%'";
                }
            }
        }
        $sql = "select a.number,b.batch,b.expiry,b.company_type,b.company_value,b.offline_type,b.offline_value,c.realname,c.mobile,d.name,d.tel from mq_card a LEFT JOIN mq_batch b ON a.batch=b.batch LEFT JOIN mq_sale c ON a.sales_id=c.id LEFT JOIN mq_offline d ON a.offline_id=d.id";
        $data = Db::query($sql.$where);

        //遍历数组  将截止日期格式化
        foreach($data as $k=>$v){
            $expiry = $v['expiry'];
            $data[$k]['expiry'] = date('Y-m-d',$expiry);

            if($v['company_type'] == 1){
                $data[$k]['company_type'] = '折扣';
            }elseif($v['company_type'] == 2){
                $data[$k]['company_type'] = '金额';
            }

            if($v['offline_type'] == 1){
                $data[$k]['offline_type'] = '折扣';
            }elseif($v['offline_type'] == 2){
                $data[$k]['offline_type'] = '金额';
            }
        }

        $header = [ '优惠码', '批次码', '截止日期', '客户优惠类型', '客户优惠值(折/元)','快递优惠类型','快递优惠值(折/元)','销售姓名','销售电话','快递姓名','快递电话'];
        if ($error = \Excel::export($header, $data, "示例Excel导出", '2007')) {
            throw new Exception($error);
        }

        export_excel($header,$data,$name = null);
    }

}
